package com.defysoft.waukids.slide;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity;
import com.defysoft.waukids.Data_Sharedpreferences;
import com.defysoft.waukids.PublicSharedpreferences;
import com.defysoft.waukids.R;
import com.defysoft.waukids.Sqlite_Connect;
import com.defysoft.waukids.notice.NoticeDetailActivity;

public class Main_Slide_Myprofile extends BaseActivity implements
		OnClickListener {
	Toolbar toolbar;
	View spinnerView;
	EditText editText[] = new EditText[5];
	Button button[] = new Button[2];

	String PK_Mem_Email, Mem_Name, Mem_Rank, nowPass, newPass;

	PublicSharedpreferences psf;
	SharedPreferences.Editor editor, editor_student;
	Data_Sharedpreferences.SF_Member member;

	public Sqlite_Connect sqlite_Connect;
	
	int pw_check = 0;
	private final int CHANGE_PASS = 1;
	private final int SUCCESS_CHANGE = 2;
	private final int FAIL_CHANGE = 3;
	private final int LOGOUT_THREAD = 4;
	private final int SUCCESS_LOGOUT = 5;
	private final int FAIL_LOGOUT = 6;
	private final int WITHDRAW_THREAD = 7;
	private final int SUCCESS_WITHDRAW = 8;
	private final int FAIL_WITHDRAW = 9;
	private final int PWCHECK_THREAD = 10;
	private final int SUCCESS_PWCHECK = 11;
	private final int FAIL_PWCHECK = 12;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.main_slide_myprofile_activity);
		psf = new PublicSharedpreferences(this);
		psf.setMembersp();
		member = psf.getMembersp();
		editor = psf.getMember_edit();
		PK_Mem_Email = member.Email;
		Mem_Name = member.Name;
		Mem_Rank = member.Rank;
		if (PK_Mem_Email == null || PK_Mem_Email == "") {
			Toast.makeText(this, "잘못된 접근입니다.", Toast.LENGTH_SHORT).show();
		}
		setStartData();
		setToolbar();

		registerReceiver(mToastMessageReceiver, new IntentFilter(
				"com.defysoft.waukids.TOAST_MESSAGE"));
	}

	@Override
	public void setStartData() {
		super.setStartData();
		sqlite_Connect = new Sqlite_Connect(this);
		editText[0] = (EditText) findViewById(R.id.MAIN_SLIDE_MYPROFILE_EDITTEXT_ID);
		editText[1] = (EditText) findViewById(R.id.MAIN_SLIDE_MYPROFILE_EDITTEXT_NAME);
		editText[2] = (EditText) findViewById(R.id.MAIN_SLIDE_MYPROFILE_EDITTEXT_NOWPASS);
		editText[3] = (EditText) findViewById(R.id.MAIN_SLIDE_MYPROFILE_EDITTEXT_NEWPASS_ONE);
		editText[4] = (EditText) findViewById(R.id.MAIN_SLIDE_MYPROFILE_EDITTEXT_NEWPASS_TWO);
		button[0] = (Button) findViewById(R.id.MAIN_SLIDE_MYPROFILE_BUTTON_LOGOUT);
		button[1] = (Button) findViewById(R.id.MAIN_SLIDE_MYPROFILE_BUTTON_WITHDRAW);
		editText[0].setText(PK_Mem_Email);
		editText[1].setText(Mem_Name);

		for (int i = 0; i < button.length; i++) {
			button[i].setOnClickListener(this);
		}
		// 비밀번호2 동일 확인
		editText[4].addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				final String ss = s.toString();
				if (ss.equals(editText[3].getText().toString())) {
					Toast.makeText(Main_Slide_Myprofile.this,
							"새로운 비밀번호 확인이 일치합니다.", Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
	}

	private void setToolbar() {
		spinnerView = findViewById(R.id.MAIN_SLIDE_MYPROFILE_TOOLBAR_VIEW);
		spinnerView.setOnClickListener(this);
		toolbar = (Toolbar) findViewById(R.id.MAIN_SLIDE_MYPROFILE_TOOLBAR);
		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	@Override
	public void startThread(int choice) {
		super.startThread(choice);
		final int cho = choice;
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				switch (cho) {
				case CHANGE_PASS:
					changePass();
					break;
				case LOGOUT_THREAD:
					logoutThread();
					break;
				case WITHDRAW_THREAD:
					withdrawThread();
					break;
				case PWCHECK_THREAD:
					pwcheckThread();
					break;
				}
			}
		});
		startDIal();
		firstThread.start();
	}

	/** 패스워드체크(새로운 비번 없을때) */
	protected void pwcheckThread() {
		JSONObject jsonObject = null;
		try {
			jsonObject = new JSONObject(publicHttpCallback(HTTP_URL, "code="
					+ CODE_MAIN_SLIDE_MYPROFILE_CHANGE + "&PK_Mem_Email="
					+ PK_Mem_Email + "&Mem_Name="
					+ editText[1].getText().toString() + "&nowpass=" + nowPass
					+ "&newpass=0&type=CHECK"));
			if (jsonObject.getBoolean("success")) {
				
				onNetworkCallback(SUCCESS_PWCHECK,
						jsonObject.getString("payload"));
			} else {
				onNetworkCallback(FAIL_PWCHECK, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString()+" where pwcheckThread()");
		}
	}

	/** 회원탈퇴 */
	protected void withdrawThread() { // 회원탈퇴
		JSONObject jsonObject = null;
		try {
			jsonObject = new JSONObject(publicHttpCallback(HTTP_URL, "code="
					+ CODE_MAIN_SLIDE_MYPROFILE_WITHDRAW + "&PK_Mem_Email="
					+ PK_Mem_Email + "&Mem_Pass="
					+ editText[2].getText().toString() + "&Mem_Rank="
					+ member.Rank));
			if (jsonObject.getBoolean("success")) {
				onNetworkCallback(SUCCESS_WITHDRAW,
						jsonObject.getString("payload"));
			} else {
				onNetworkCallback(FAIL_WITHDRAW,
						jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString()+" where withdrawThread()");
		}
		;
	}

	/** 로그아웃 */
	protected void logoutThread() { // 로그아웃스레드.
		JSONObject jsonObject = null;
		try {
			jsonObject = new JSONObject(publicHttpCallback(HTTP_URL, "code="
					+ CODE_MAIN_SLIDE_MYPROFILE_LOGOUT + "&PK_Mem_Email="
					+ PK_Mem_Email));
			if (jsonObject.getBoolean("success")) {
				onNetworkCallback(SUCCESS_LOGOUT,
						jsonObject.getString("payload"));
			} else {
				onNetworkCallback(FAIL_LOGOUT, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString()+" where logoutThread()");
		}
		;
	}

	/** 정보변경 */
	protected void changePass() {
		JSONObject jsonObject = null;
		try {
			jsonObject = new JSONObject(publicHttpCallback(HTTP_URL, "code="
					+ CODE_MAIN_SLIDE_MYPROFILE_CHANGE + "&PK_Mem_Email="
					+ PK_Mem_Email + "&Mem_Name="
					+ editText[1].getText().toString() + "&nowpass=" + nowPass
					+ "&newpass=" + newPass + "&type=CHANGE"));
			if (jsonObject.getBoolean("success")) {
				onNetworkCallback(SUCCESS_CHANGE,
						jsonObject.getString("payload"));
			} else {
				onNetworkCallback(FAIL_CHANGE, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION,  e.toString()+" where changePass()");
		}
	}

	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);
		switch (_message.what) {
		case SUCCESS_CHANGE: // 정보변경 완료.
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT)
					.show();
			editor.clear();
			editor.commit();
			setResult(REFRESH_CODE);
			finish();
			break;

		case FAIL_CHANGE:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT)
					.show();
			break;
		case SUCCESS_PWCHECK: // 비밀번호 체크 완료.
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			pw_check = 1;
			checkPass();
			break;

		case FAIL_PWCHECK:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT)
					.show();
			pw_check = 0;
			break;

		case SUCCESS_LOGOUT: // 로그아웃 완료.
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT)
					.show();
			//학부모일때는 자녀값 초기화.
			if (member.Rank.equals("3")) {
				psf.setStudentsp();
				editor_student = psf.getStudent_edit();
				editor_student.clear();
				editor_student.commit();
			}
			//맴버
			editor.clear();
			editor.commit();
			//학원
			psf.setSchoolsp();
			editor = psf.getSchool_edit();
			editor.clear();
			editor.commit();			
			//반
			psf.setClasssp();
			editor = psf.getClass_edit();
			editor.clear();
			editor.commit();
			
			setResult(REFRESH_CODE);
			finish();
			break;

		case FAIL_LOGOUT:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT)
					.show();
			break;

		case SUCCESS_WITHDRAW: // 회원탈퇴 완료.
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT)
					.show();
			editor.clear();
			editor.commit();
			setResult(REFRESH_CODE);
			finish();
			break;

		case FAIL_WITHDRAW:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT)
					.show();
			break;

		case CATCH_EXCEPTION:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			sqlite_Connect.insert_Err_Log((String)_message.obj,android.os.Build.VERSION.SDK_INT,"Main_Slide_Myprofile", member.Email);
			pw_check = 0;
			break;
		}
	}

	@Override
	public void onClick(View v) {
		int check_withdraw = 0;
		switch (v.getId()) {
		case R.id.MAIN_SLIDE_MYPROFILE_TOOLBAR_VIEW: // 비밀번호 바꾸기 클릭.
			checkPass(); // 입력 양식 확인
			break;
		case R.id.MAIN_SLIDE_MYPROFILE_BUTTON_LOGOUT: // 로그아웃 클릭.
			alertDialog("로그아웃 하겠습니까?", LOGOUT_THREAD);
			break;
		case R.id.MAIN_SLIDE_MYPROFILE_BUTTON_WITHDRAW: // 회원탈퇴 클릭.
			if (editText[2].getText().toString().length() <= 0) {
				Toast.makeText(Main_Slide_Myprofile.this,
						"회원탈퇴를 진행하기 위해 기존 비밀번호를 입력하세요.", Toast.LENGTH_SHORT)
						.show();
				editText[2].setHint("현재 비밀번호를 입력해주세요.");
				editText[2].setHintTextColor(Color.RED);
				check_withdraw = 1;
			}
			if (check_withdraw == 0) {
				alertDialogFirst("회원탈퇴 하겠습니까?", WITHDRAW_THREAD);
			}
			break;

		}
	}

	// 새로운 비밀번호 양식 확인
	private void checkPass() {
		int check = 0;
		nowPass = editText[2].getText().toString(); // 기존 비밀번호.
		newPass = editText[3].getText().toString(); // 새로운비번.

		if (editText[1].getText().toString().length() <= 0) {
			editText[1].setHint("사용 이름을 입력하세요.");
			editText[1].setHintTextColor(Color.RED);
			check = 1;
		} else if (editText[2].getText().toString().length() <= 0) {
			editText[2].setHint("현재 비밀번호를 입력해주세요.");
			editText[2].setHintTextColor(Color.RED);
			check = 1;
		} else if (editText[3].getText().toString().length() <= 0
				&& editText[4].getText().toString().length() <= 0) { // 새로운 비번이
																		// 없을때.
			if (pw_check == 0) {
				startNetwork(PWCHECK_THREAD);
				check = 1;
			} else if (pw_check == 1) {
				editText[3].setHint("새 비밀번호를 입력해 주세요.");
				editText[3].setHintTextColor(Color.RED);
				showPopup(
						"알림",
						"새 비밀번호를 입력하세요.\n비밀번호 변경을 원하지 않을경우,\n기존 비밀번호를 입력해 주세요.",
						0);
				check = 1;
			}
		} else if (editText[3].getText().toString().length() > 0) { // 새 비밀번호를
																	// 입력했을
																	// 경우에만.
			if (pw_check == 0) {
				startNetwork(PWCHECK_THREAD);
				check = 1;
			} else if (pw_check == 1) {
				if (editText[3].getText().length() < 8
						|| editText[3].getText().length() > 15) {
					editText[3].setText("");
					editText[3].setHint("패스워드를 8자~15자로 입력하세요.");
					editText[3].setHintTextColor(Color.RED);
					check = 1;
				} else if (editText[4].getText().toString().length() < 0) {
					editText[4].setHint("새 비밀번호 확인을 입력해주세요.");
					editText[4].setHintTextColor(Color.RED);
					check = 1;
				} else if (!editText[4].getText().toString()
						.equals(editText[3].getText().toString())) {
					editText[4].setText("");
					editText[4].setHint("새로운 비밀번호가 일치하지 않습니다.");
					editText[4].setHintTextColor(Color.RED);
					check = 1;
				}
			}
		}
		if (check == 0) {
			startNetwork(CHANGE_PASS);
		}
	}

	// 네.아니오.선택다이얼로그
	void alertDialog(String string_title, int int_code) {
		final String title = string_title;
		final int code = int_code;
		AlertDialog.Builder builder = new AlertDialog.Builder(
				Main_Slide_Myprofile.this);
		AlertDialog alert;
		builder.setMessage(title)
				.setCancelable(false)
				.setPositiveButton("네", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						startNetwork(code);
					}
				})
				.setNegativeButton("아니오",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.cancel();
							}
						});
		alert = builder.create();
		alert.show();
	}
	// 회원탈퇴 1차용.
	void alertDialogFirst(String string_title, int int_code) {
		final String title = string_title;
		final int code = int_code;
		AlertDialog.Builder builder = new AlertDialog.Builder(
				Main_Slide_Myprofile.this);
		AlertDialog alert;
		builder.setMessage(title)
		.setCancelable(false)
		.setPositiveButton("네", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				//alertDialog("사용하고 계신 아이디("+member.Email+")는 탈퇴할 경우 재사용 및 복구가 불가능 합니다.\n탈퇴한 아이디는 본인과 타인 모두 재사용 및 복구가 불가하오니 신중하게 선택하시기 바랍니다.\n서비스에 남아 있는 게시글은 탈퇴 후 삭제할 수 없습니다.\n탈퇴 하시겠습니까?", WITHDRAW_THREAD);
				alertDialog("서비스에 남아 있는 게시글은 탈퇴 후 삭제할 수 없습니다.\n탈퇴 하시겠습니까?", WITHDRAW_THREAD);
			}
		})
		.setNegativeButton("아니오",
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog,
					int which) {
				dialog.cancel();
			}
		});
		alert = builder.create();
		alert.show();
	}

	private final BroadcastReceiver mToastMessageReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(
					R.layout.toast_layout, null);
			TextView toast_tv = (TextView) layout
					.findViewById(R.id.TOAST_LAYOUT_TV);
			Toast toast = new Toast(Main_Slide_Myprofile.this);
			toast.setView(layout);
			toast_tv.setText(intent.getStringExtra("PUSH_NAME") + " : "
					+ intent.getStringExtra("PUSH_SUB"));
			toast.setDuration(Toast.LENGTH_LONG);
			toast.show();
		}
	};

}
